# -*- coding: utf-8 -*-
# @Time    : 2018/2/5 13:11
# @Author  : Soft
# @File    : controller.py
# @Desc    : 用户界面控制器
from config import *
from module.AuthUtil import auth_required
from module.ExeclUtils.StuExecl import getStuExecl, readStuExecl
from module.TimeUtils import *
from module.user import user, u_login
from flask import render_template, request, jsonify, make_response, send_file, current_app
from module.user.service import StuService
from module.cache import cache
from module.admin import ad_login
from module.class_.service import ClzService
from module.record.service import ReService
from module.work.service import WorkService
# import requests
from module.z_study.service import Z_StudyService

cache.set('reg_lock', False)  # 用户注册锁 True禁止 False开放


@u_login.loader
def get_u(uid):
    return StuService.get_name_pass(uid)


@user.route('/lock/<can>', methods=['post'])
@ad_login.required
def lock(can):
    if can == 'open':
        cache.set('reg_lock', False)
    else:
        cache.set('reg_lock', True)
    return jsonify(status=True, lock=cache.get('reg_lock'))


@user.route('/login', methods=['post', 'get'])
def login():
    if request.method == 'GET':
        prev_url = request.args.get('prev')
        if prev_url:
            ip = request.host[:-1]  # flag 使用当前ip验证
            prev_url = prev_url + "?flag=" + ip
        return render_template('login.html', prev_url=prev_url)
    elif request.method == 'POST':
        name = request.form.get('username')
        password = request.form.get('password')
        remember = request.form.get('remember')
        result = StuService.login(name, password)
        if result[0]:
            res = make_response(jsonify(status=True))
            if remember == 'true':
                u_login.login(res, result[1].id, result[1].stu_id, result[1].stu_pass, remember=True)
            else:
                u_login.login(res, result[1].id, result[1].stu_id, result[1].stu_pass)
            return res
        return jsonify(status=False, msg='登录失败')


@user.route('/logout', methods=['post'])
@u_login.required
def logout():
    res = make_response(jsonify(status=True))
    return u_login.logout(response=res)


@user.route('/register', methods=['post', 'get'])
def register():
    if request.method == 'GET':
        return render_template('register.html')
    elif request.method == 'POST':
        if cache.get('reg_lock'):
            return jsonify(status=False, msg='没有开放用户注册功能')
        users = request.form.to_dict()
        code = users.pop('code')
        if code != YQ_CODE:
            return jsonify(status=False, msg='邀请码错误')
        s_name = users.get('stu_id')
        if StuService.query_stu_id(stu_id=s_name):
            return jsonify(status=False, msg='账户已存在')
        if StuService.add(**users):
            return jsonify(status=True)
        return jsonify(status=False, msg='内部错误')


@user.route('/delete/<uid>', methods=['post'])
@ad_login.required  # 拥有超级管理权限才能删除用户
def delete(uid):
    if ad_login.get_user_name() != 'admin':
        return jsonify(status=False, msg='你不是超级管理员不能删除学生！')
    if StuService.remove(uid=uid):
        return jsonify(status=True)
    return jsonify(status=False, msg='数据库错误')


@user.route('/get_back', methods=['post', 'get'])
def get_back():
    if request.method == 'GET':
        return render_template('get_back.html')
    elif request.method == 'POST':
        stu_id = request.form.get('username')
        stu_pass = request.form.get('password')
        stu_tel = request.form.get('tel')
        stu = StuService.query_stu_id(stu_id=stu_id)
        if not stu:
            return jsonify(status=False, msg='账号不存在！')
        if stu.get('stu_tel') != stu_tel:
            return jsonify(status=False, msg='手机号码错误！')
        if StuService.change(stu_id=stu_id, stu_pass=stu_pass):
            return jsonify(status=True, msg=stu_pass)
        return jsonify(status=False, msg='未知错误！')


@user.route('/change', methods=['post', 'get'])
@u_login.required
def change():
    if request.method == 'GET':
        return render('change.html')
    elif request.method == 'POST':
        stu = dict(request.form.to_dict())
        for k, v in stu.items():
            if len(v) <= 0:
                stu.pop(k)
        if stu.has_key('stu_id'):
            stu_id = stu.pop('stu_id')
            if StuService.change(stu_id=stu_id, **stu):
                return jsonify(status=True)
            return jsonify(status=False, msg='未知错误')
        return jsonify(status=False, msg='账户不存在')


@user.route('/change_mm', methods=['get'])
@u_login.required
def change_mm():
    return render('change_mm.html')


@user.route('/by_name', methods=['post'])
@ad_login.required
def get_by_name():
    stu_name = request.form.get('stu_name')
    stus = StuService.query_name(real_name=stu_name)
    return jsonify(status=True, result=stus)


@user.route('/by_year', methods=['post'])
@auth_required
def get_by_year():  # 根据注册年度获取用户
    year = request.form.get('year', '2018')
    stus = StuService.by_year(year=year)
    return jsonify(status=True, result=stus)


@user.route('/about')
def about():
    return render_template('about.html')


@user.route('/')
@user.route('/home')
@u_login.required
def home():
    sid = u_login.get_user_id()
    one_up = True  # 是否第一次交作业
    now_clz = ClzService.get_now_clazz()
    if now_clz:
        now_clz['k_work_endtime'] = now_clz.get('k_work_endtime')[:-5]
        kid = now_clz.get('id')
        if WorkService.is_has(sid=sid, kid=kid)[0]:
            one_up = False
    next_clz = ClzService.get_next_clazz()
    data = dict(now_clz=now_clz, next_clz=next_clz, one_up=one_up)
    return render('home.html', data=data)


@user.route('/class')
@u_login.required
def class_():
    year = get_year()
    y_group = ClzService.get_year_group()
    if len(y_group) == 1:
        year = y_group[0].get('k_time')
    years = [year]
    years.extend(y_group)
    clz = ClzService.pages(page=1, year=year)
    data = dict(years=years, clz_list=clz)
    return render('class.html', data=data)


@user.route('/record')
@u_login.required
def record():
    sid = u_login.get_user_id()
    year = get_year()
    y_group = StuService.get_year_group()
    if len(y_group) == 1:
        year = y_group[0].get('stu_reg_time')
    years = [year]
    years.extend(y_group)
    records = ReService.pages(page=1, year=year, stu_id=sid)
    data = dict(years=years, records=records)
    # print data
    return render('record.html', data=data)


@user.route('/check')
@u_login.required
def check():
    """
    控制学生签到页面 在规定时间内才能签到和请假
    """
    now_date = get_date()
    k_can = ClzService.by_k_time(k_time=now_date)
    can = zs = False
    if k_can[0]:
        k_start_time = k_can[1].k_time
        if check_limit(k_start_time) == Check.CD or check_limit(k_start_time) == Check.CQ:
            can = True
        else:
            can = Check.ALL_DAY_CHECK
    if not can:
        if Z_StudyService.can_check():
            can = True
            zs = True
    return render('check.html', data={'can': can, 'k_has': k_can[0], 'clazz': k_can[1], 'zs': zs,
                                      'local': cache.get("local")})


@user.route('/export')
@ad_login.required
def export():
    year = request.args.get('year', '2018')
    page = StuService.pages(1, 20000, year=year)
    students = page.get("result")
    filename = getStuExecl(students)
    return send_file(filename, as_attachment=True, attachment_filename='用户数据.xls')


@user.route('/import', methods=['post'])
@ad_login.required
def import_():
    xlstu = request.files['student']
    try:
        if xlstu.filename.endswith('.xls'):
            temp = current_app.root_path + '/module/ExeclUtils/temp/student.xls'
            xlstu.save(temp)
            readStuExecl()
            return jsonify(status=True)
        return jsonify(status=False, msg='仅支持execl文件！')
    except BaseException as e:
        return jsonify(status=False, msg=e)


# @user.route('/parse_qr', methods=['post'])
# @u_login.required
# def parse_qr():
#     file_blob = request.files.get('file')
#     url = 'http://123.206.7.80:10082/api/parse'
#     data = {
#         'auth': 'lkl123456'
#     }
#     files = {
#         'file': file_blob
#     }
#     res = requests.post(url, data=data, files=files)
#     return res.text

def render(view, data=None):
    u_id = u_login.get_user_id()
    stu = StuService.find_by_id(u_id)
    if stu:
        return render_template(view, username=stu.stu_name, stu=stu, data=data)
    return render_template("error/404.html")
